package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink04_Process_SideOutPut {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.读取端口数据并转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = env.socketTextStream("hadoop102", 9999)
                .map(line -> {
                    String[] fields = line.split(",");
                    return new WaterSensor(fields[0],
                            Long.parseLong(fields[1]),
                            Double.parseDouble(fields[2]));
                });

        //3.使用ProcessFunction实现分流功能
        SingleOutputStreamOperator<WaterSensor> processDS = waterSensorDS.process(new ProcessFunction<WaterSensor, WaterSensor>() {

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {

                //取出数据中的水位线值
                Double vc = value.getVc();

                if (vc <= 30.0D) {
                    //输出数据到主流
                    out.collect(value);
                } else {
                    ctx.output(new OutputTag<String>("sideOutPut") {
                               },
                            value.getId() + "," + vc);
                }

            }
        });

        //4.打印主流和侧输出流数据
        processDS.print("Main>>>>>>>>>>");
        processDS.getSideOutput(new OutputTag<String>("sideOutPut") {
        }).print("SideOutPut>>>>>>>>>>>>>>");

        //5.启动
        env.execute();

    }

}
